package com.fivestar.pmanager.web.tag;

import org.apache.commons.io.FilenameUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fivestar.pmanager.core.util.ToolUtil;
import com.fivestar.pmanager.model.SysDictBean;
import com.fivestar.pmanager.model.SysModuleBean;
import com.fivestar.pmanager.service.SysDictService;
import com.fivestar.pmanager.service.SysOperationService;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.fivestar.pmanager.constants.CommonConstants.SESSION_KEY_SUPPORT_USER;
import static com.fivestar.pmanager.constants.CommonConstants.USER_IDENTITY_OPERATOR;
import static com.fivestar.pmanager.core.util.CodeHelper.isNotNull;
import static com.fivestar.pmanager.core.util.JsonUtil.writeObject2Json;
import static com.fivestar.pmanager.core.util.SpringUtil.getBean;

/**
 * 系统el表达式
 *
 */
@SuppressWarnings("all")
public class SysElTag
{

    private static final Logger log = LoggerFactory.getLogger(SysElTag.class);

    /**
     * 序列化json字符串
     *
     * @param o
     * @return
     * @throws JsonGenerationException
     * @throws JsonMappingException
     * @throws IOException
     */
    public static String json(Object o) throws JsonGenerationException, JsonMappingException, IOException
    {
        if(isNotNull(o))return writeObject2Json(o);
        return null;
    }

    public static String module(HttpServletRequest request)
    {
        SysOperationService sysOperationService = getBean(SysOperationService.class);
        String requestUrl = getRequestUrl(request);
        SysModuleBean module = sysOperationService.findModuleByOperation(requestUrl);
        if(module != null) {
            log.info("@_@:{}", module.getModuleName());
            return module.getModuleCode();
        }

        return "";
    }

    public static boolean checkedMenu(int level, String willCheckedModuleCode, String testModuleCode)
    {
    	if(willCheckedModuleCode == null || willCheckedModuleCode.length() == 0 || (level * 3) > willCheckedModuleCode.length()) return false;
        return willCheckedModuleCode.substring(0, (level * 3)).equals(testModuleCode);
    }

    public static List<SysDictBean> dicts(String name)
    {
        HttpServletRequest request = ToolUtil.getRequest();
        List<SysDictBean> dicts = (List<SysDictBean>) request.getAttribute(name);
        if(dicts == null)
        {
            SysDictService smDictService = getBean(SysDictService.class);
            dicts = smDictService.findByName(name);
            request.setAttribute(name, dicts);
        }
        return dicts;
    }


    public static String dict(String name,String code)
    {
        HttpServletRequest request = ToolUtil.getRequest();
        SysDictBean smDictBean = (SysDictBean) request.getAttribute(name+code);
        if(smDictBean == null)
        {
        	SysDictService smDictService = getBean(SysDictService.class);
            smDictBean = smDictService.findByNameAndCode(name, code);
            request.setAttribute(name+code, smDictBean);
        }
        return smDictBean == null ? "" : smDictBean.getValue();
    }

    private static String getRequestUrl(HttpServletRequest request)
    {
        String contentPath = request.getContextPath();
        String requestUrl = request.getRequestURI().substring(contentPath.length());
        if(requestUrl.contains("?"))
        {
            requestUrl = requestUrl.substring(0,requestUrl.lastIndexOf("?"));
        }
        return requestUrl;
    }


    /**
     * 将数据库字段转换成java属性
     * @return
     */
    public static String dbFieldToProperty(String s)
    {
        if(s != null && s.length() > 0)
        {
            s = s.toLowerCase();
            StringBuilder property = new StringBuilder();
            String [] strArray = s.split("_");
            property.append(strArray[0]);
            for(int i = 1; i < strArray.length; i++)
            {
                String str = strArray[i];
                if(str != null && str.length() > 0) property.append(str.substring(0,1).toUpperCase());
                if(str != null && str.length() > 2) property.append(str.substring(1));
            }
            return property.toString();
        }
        return s;
    }


//    public static String file(String src)
//    {
//        String suffix = FilenameUtils.getExtension(src);
//        if(("jpg;png;jpeg;gif;bmp".contains(suffix.toLowerCase())))
//        {
//           return getImageFileServerUrl() + src;
//        }
//        return getFileServerUrl() + src;
//    }


    public static Date now()
    {
        return new Date();
    }

    public static String now(String pattern)
    {
        return new SimpleDateFormat(pattern).format(now());
    }

    public static double random()
    {
        return Math.random();
    }

}
